<?php
class AppForumThread extends AppModel { 

    var $name = 'AppForumThread'; 
    
    var $useDbConfig = 'liteapp';
    var $defaultDbConfig = 'liteapp_slave';
    var $masterDbConfig = 'liteapp';
    
    var $content_to_oss = true; //将内容保存到OSS
    
    // 仅为微信文章模块时，才分表处理。
    var $actsAs = array('SplitModel'=> array( 'field'=> 'app_id','split'=> 256 ));
    
    var $app_id = null;
    var $content = null;
    
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
    }
    
    public function beforeSave($options = array())
    {
        parent::beforeSave($options);
        
        $this->content = $this->data['AppForumThread']['content'] ;
        $this->app_id = $this->data['AppForumThread']['app_id'] ;
        unset($this->data['AppForumThread']['content']);
        return true;
    }
    
    public function afterSave($created = false) {
        parent::afterSave($created);
        
        $id =  $this->id;
        if( $this->content_to_oss && $id && $this->content ){
            App::uses('CrawlUtility', 'Utility');
            CrawlUtility::saveToAliOss($this->content, '/aftcontent/'.$this->app_id.'/'.$id,false,true);
        }
        return true;
    }
    
    public function beforeDelete($cascade = true) {
        parent::beforeDelete($cascade);
        $this->delete_id = $this->id;
    }
    
    public function afterDelete(){
        if( $this->content_to_oss && $this->delete_id ){
            App::uses('CrawlUtility', 'Utility');
            $object_name = '/aftcontent/'.$this->app_id.'/'. $this->delete_id;
            if(! CrawlUtility::delFromAliOss( $object_name )) {
                // 删除数据后，删除OSS中存储的内容
                CakeLog::info("delete from oss $object_name  failed");
            }
        }
        parent::afterDelete();
    }
    
    public function afterFind($results, $primary = false) {    
        if( $this->content_to_oss ) {
            App::uses('CrawlUtility', 'Utility');
            try{
                $total = count($results);
                if($total == 1 || $this->recursive ==1) { // 只有一条，或者要拉取所有相关记录
                    foreach($results as &$item) {
                        $app_id = $item['AppForumThread']['app_id'];
                        $content = CrawlUtility::getFromAliOss('/aftcontent/'.$app_id.'/'.$item['AppForumThread']['id']);                        
                        $item['AppForumThread']['content'] = $content; // 有内容时，才使用值，否则使用数据库中的值。兼容数据库中已有的数据
                    }
                }
            }
            catch(Exception $e){
                return $results;
            }
        }
        return $results;
    }
} 
?>